#include "QDebugStream.h"
#include <iostream>

QDebugStream::QDebugStream(std::ostream& stream, QPlainTextEdit* text_edit, QString colorCode)
    : m_stream(stream),
      m_colorCode(colorCode)
{
    log_window = text_edit;
    m_old_buf = stream.rdbuf();
    stream.rdbuf(this);

    connect(this, SIGNAL(sendString(QString)), text_edit, SLOT(appendHtml(QString)));
}

QDebugStream::~QDebugStream()
{
    // output anything that is left
    if(!m_string.empty())
    {
        emit sendString(createColoredText(m_string));
    }

    log_window->appendHtml(createColoredText(m_string));
    m_stream.rdbuf(m_old_buf);
}

int QDebugStream::overflow(int v)
{
    mutex.lock();      
    if(v == '\n')
    {
        emit sendString(createColoredText(m_string));
        m_string.erase(m_string.begin(), m_string.end());
    }
    else
        m_string += v;

    mutex.unlock();
    return v;
}

std::streamsize QDebugStream::xsputn(const char* p, std::streamsize n)
{
    mutex.lock();

    m_string.append(p, p + n);
    size_t pos = 0;
    while(pos != std::string::npos)
    {
        pos = m_string.find('\n');
        if(pos != std::string::npos)
        {
            std::string tmp(m_string.begin(), m_string.begin() + pos);
            emit sendString(createColoredText(tmp));
            m_string.erase(m_string.begin(), m_string.begin() + pos + 1);
        }
    }
    mutex.unlock();
    return n;
}

QString QDebugStream::createColoredText(const std::string& s)
{
    QString htmlString = "<font color=\"";
    htmlString.append(m_colorCode);
    htmlString.append("\">");
    htmlString.append(m_string.c_str());
    htmlString.append("</font");

    return htmlString;
}